package wsz.rocketMq.init;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import wsz.rocketMq.dao.PhoneDao;
import wsz.rocketMq.entity.Phone;
import wsz.rocketMq.util.Constants;

import java.util.List;

/**
 * 应用启动后，进行数据的初始化
 * @author wsz
 * @date 2022/3/2 12:43
 **/
@Slf4j
@Component
public class ApplicationInit implements ApplicationRunner {

    @Autowired
    private PhoneDao phoneDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 数据初始化
        initPhone();
        initRedis();
    }

    private void initPhone() {
        List<Phone> all = phoneDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            return;
        }
        // 数据初始化
        Phone myPhone = new Phone();
        myPhone.setName("小米11 Ultra");
        myPhone.setPrice(6999.00);
        phoneDao.save(myPhone);

        log.info("phone商品已初始化");
    }

    private void initRedis() {
        String value = redisTemplate.opsForValue().get(Constants.KILL_PHONE_KEY);
        log.info("phone库存为:" + value);
        try {
            if (Strings.isNullOrEmpty(value)) {
                redisTemplate.opsForValue().set(Constants.KILL_PHONE_KEY, String.valueOf(Constants.KILL_PHONE_KNUMBER));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
